package de.stefanocke.roo.wicket.templates

import de.stefanocke.roo.wicket.Stereotypes

class FormTemplate extends JavaHtmlTemplate{
	
	override String javaClassNameWhenNew(){
		"FormPanel"
	}
	
	override String stereotype(){
		Stereotypes::FORM
	}
	
	override subPackageToUseWhenNew(){
		"common"
	}
		
	override buildJavaContents(){
		import_("org.apache.wicket.feedback.ContainerFeedbackMessageFilter")
		import_("org.apache.wicket.markup.html.form.Form")
		import_("org.apache.wicket.markup.html.panel.FeedbackPanel")
		import_("org.apache.wicket.markup.html.panel.Panel")
		import_("org.apache.wicket.model.IModel")
		'''	
		«stereotypeAnnotation»
		public abstract class «simpleTypeName»<T> extends Panel {
		
			private static final long serialVersionUID = 1L;
			
			private Form<T> form;
			private FormFieldsPanel<T> formFields;
		
			protected «simpleTypeName»() {
				super("INVALID");
				throw new UnsupportedOperationException("Do not use this constructor since it is only a workaround for ITD issues");
			}
		
			public «simpleTypeName»(String id, IModel<T> model) {
				super(id, model);	
				form = createForm();
				form.add(createFeedbackPanel());
				formFields = createFormFields(model); 
				form.add(formFields);
				add(form);
				//we set the model late so the children get informed...
				form.setModel(model);
				formFields.setModel(model);
			}
		
			@SuppressWarnings("unchecked")
			@Override
			protected void onModelChanged() {
				//Propagate the model change to the form
				form.setModel((IModel<T>) getDefaultModel());
				formFields.setModel((IModel<T>) getDefaultModel());
				super.onModelChanged();
			}
		
			protected FeedbackPanel createFeedbackPanel() {
				return new FeedbackPanel("feedback", new ContainerFeedbackMessageFilter(this));
			}
		
			protected abstract FormFieldsPanel<T> createFormFields(IModel<T> cmp);
		
			protected Form<T> createForm() {
				return new Form<T>("form"){
					/***/
					private static final long serialVersionUID = 1L;
		
					@Override
					protected void onSubmit() {
						T modelObject = getForm().getModelObject();
						persist(modelObject);
						postPersist(modelObject);
					}
				};
			}
		
			public Form<T> getForm() {
				return form;
			}
		
			protected abstract void persist(T t);
		
			protected void postPersist(T modelObject){
			}
		
		}
		'''
	}
	
	override buildHtmlBody(){
		'''
		<wicket:panel xmlns:wicket="http://wicket.sourceforge.net/">
			<form wicket:id="form">
				<fieldset>
					<legend>Foo</legend>
					<div class="fieldset">
						<span class="feedback" wicket:id="feedback"></span>
						<span wicket:id="formfields"></span>
					</div>
				</fieldset>
				<fieldset class="submit">
					<input type="submit" value="Save"></input>
				</fieldset>
			</form>
		</wicket:panel>
		'''
	}
}